package dynamic.mybatisplus.extension.plugins.pagination.dialects;

import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;


import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class SQLServer2005Dialect implements IDialect{

    private static final Pattern pattern = Pattern.compile("\\((.)*order by(.)*\\)");

    public String getOrderByPart(String sql) {
        String order_by = "order by";
        int lastIndex = sql.toLowerCase().lastIndexOf(order_by);
        if (lastIndex == -1) {
            return StringPool.EMPTY;
        }
        Matcher matcher = pattern.matcher(sql);
        if (!matcher.find()) {
            return sql.substring(lastIndex);
        }
        int end = matcher.end();
        return lastIndex < end ? StringPool.EMPTY : sql.substring(lastIndex);
    }

    @Override
    public DialectModel buildPaginationSql(String originalSql, long offset, long limit) {
        StringBuilder pagingBuilder = new StringBuilder();
        String orderby = getOrderByPart(originalSql);
        String distinctStr = StringPool.EMPTY;

        String loweredString = originalSql.toLowerCase();
        String sqlPartString = originalSql;
        if (loweredString.trim().startsWith("select")) {
            int index = 6;
            if (loweredString.startsWith("select distinct")) {
                distinctStr = "DISTINCT ";
                index = 15;
            }
            sqlPartString = sqlPartString.substring(index);
        }
        pagingBuilder.append(sqlPartString);

        // if no ORDER BY is specified use fake ORDER BY field to avoid errors
        if (StringUtils.isBlank(orderby)) {
            orderby = "ORDER BY CURRENT_TIMESTAMP";
        }
        long firstParam = offset + 1;
        long secondParam = offset + limit;
        String sql = "WITH selectTemp AS (SELECT " + distinctStr + "TOP 100 PERCENT " +
                " ROW_NUMBER() OVER (" + orderby + ") as __row_number__, " + pagingBuilder +
                ") SELECT * FROM selectTemp WHERE __row_number__ BETWEEN " +
                //FIX#299：原因：mysql中limit 10(offset,size) 是从第10开始（不包含10）,；而这里用的BETWEEN是两边都包含，所以改为offset+1
                firstParam + " AND " + secondParam + " ORDER BY __row_number__";
        return new DialectModel(sql);
    }
}
